package com.atguigu.yygh.host.receiver;

import com.atguigu.yygh.common.service.MqConst;
import com.atguigu.yygh.common.service.RabbitService;
import com.atguigu.yygh.host.service.ScheduleService;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author DongYu Zhou
 * @date 2022/7/8 21:07
 */
@Component
public class HospitalReceiver {
    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private RabbitService rabbitService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER,durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),
            key={MqConst.ROUTING_ORDER}
    ))
    public void receiver(OrderMqVo orderMqVo, Message message , Channel channel){
        //1取出参数
        String hoscode = orderMqVo.getHoscode();
        String hosScheduleId = orderMqVo.getScheduleId();
        //2查询排班信息
        Schedule schedule =
                scheduleService.getScheduleByInfo(hoscode,hosScheduleId);
        //3更新排班
        Integer reservedNumber = orderMqVo.getReservedNumber();
        Integer availableNumber = orderMqVo.getAvailableNumber();
        //3.5判断是创建订单，还是取消预约
        if(StringUtils.isEmpty(availableNumber)){
            //取消预约
            availableNumber = schedule.getAvailableNumber()+1;
            schedule.setAvailableNumber(availableNumber);
        }else{
            schedule.setReservedNumber(reservedNumber);
            schedule.setAvailableNumber(availableNumber);
        }
        scheduleService.update(schedule);
        //4发送短信消息
        MsmVo msmVo = orderMqVo.getMsmVo();
        if(msmVo!=null){
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM,
                    MqConst.ROUTING_MSM_ITEM,msmVo);
        }
    }

}
